<?php

/**
 * 获取系统菜单
 * @return mixed
 */
function list_system_menu()
{
    return \think\facade\Config::get('system.sys_menu');
}

/**
 * [filesystem_uploader 上传图片及文件]
 * @param  [type] $dis   [description]
 * @param  string $field [description]
 * @return [type]        [description]
 */
function filesystem_uploader($dis, $field = 'file')
{
    try {
		$system = \app\common\model\System::getItemByType(2);
		$disk   = $system['upload_mode'];
		if ($disk !== 'public') {
			set_upload_conf( $system );
		}
        $file = \think\facade\Request::file($field);
        if (null === $file) {
            throw new \Exception('请上传文件', UPLOAD_ERR_NO_FILE);
        }
        validate(['file' => [
            'fileSize' => $system['upload_size'] * 1024 * 1024,
            'fileExt'  => $system['upload_ext']
        ]])->check(['file' => $file]);

        $root = \think\facade\Filesystem::disk($disk)->putFile($dis, $file, 'uniqid');
        $path = str_replace('\\', '/', $root);
         return [
            'path'  => str_replace('\\', '/', $path),
            'size'  => $file->getSize(),
            'url'   => rtrim($system['image_url'], '/') . '/' . str_replace('\\', '/', $root)
        ];
    } catch (\Exception $ae) {
        throw new \app\common\exception\AdminException($ae->getMessage());
    }
}

/**
 * 设置上传的配置信息
 * @param {Object} $config
 */
function set_upload_conf($config)
{
	if ($config['upload_mode'] === 'aliyun') {
		\think\facade\Config::set(
		[
			'disks' => [
				'aliyun' => [
					'type' => 'aliyun',
					'accessId' => $config['aliyun_access_id'],
					'accessSecret' => $config['aliyun_access_secret'],
					'bucket' => $config['aliyun_bucket'],
					'endpoint' => $config['aliyun_endpoint']
				]
			]
		]
		, 'filesystem');
		return true;
	}
	
	if ($config['upload_mode'] === 'qiniu') {
		\think\facade\Config::set(
		[
			'disks' => [
				'qiniu' => [
					'type' => 'qiniu',
					'accessKey' => $config['qiniu_access_key'],
					'secretKey' => $config['qiniu_secret_key'],
					'bucket' 	=> $config['qiniu_bucket'],
					'url' 		=> $config['image_url']
				]
			]
		]
		, 'filesystem');
		return true;
	}
	return false;
}

